'''text = "GET /index.html HTTP/1.1"

# a string of digits
m = re.match("GET .* HTTP/1\.1", text)
if m: print repr("\d+"), "=>", repr(m.group(0))
else: print "no hizo match"'''
# http://www.wellho.net/resources/ex.php4?item=y202/pyserv
# Basic web server

import socket
import re

def matchesGet(text):
	m = re.match("GET .* HTTP/1\.1", text)
	if m:
		print repr(m.group(0))
		return True
	else:
		return False

host = ''
port = 8081

sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
sock.bind((host,port))
sock.listen(1)

while 1:
        csock,caddr = sock.accept()
        cfile = csock.makefile('rw',0)
	
	request = cfile.readline().strip()
	isValidRequest = matchesGet(request)
	print "Request: ",request,"isValidRequest:",isValidRequest
	
	if request == False:
		break
        # Protocol exchange - read request

        while 1:
                line = cfile.readline().strip()
                if line == '':
			try:
				content = open("response.html","r").read()
			except:
				print "File not found: response.html"
				content = "<head><title>Eh?</title></head>"+"\n"+"<h1>GO AWAY!</h1>"
			#print content
                        cfile.write("HTTP/1.0 200 OK\n\n")
                        cfile.write(content)
                        cfile.close()
                        csock.close()
                        break
